package com.gitee.chili.leisure.message;

import com.gitee.chili.leisure.ResponseCode;
import com.gitee.chili.leisure.ResponseResult;
import com.gitee.chili.leisure.RoomManager;
import com.gitee.chili.leisure.SimpleBeanFactory;
import com.gitee.chili.leisure.core.AbstractDefaultMessage;
import com.gitee.chili.leisure.core.Packet;
import com.gitee.chili.leisure.domain.Room;
import com.gitee.chili.leisure.model.HallModel;
import com.gitee.chili.leisure.service.SpecificTaskTransferClient;
import com.gitee.chili.leisure.util.AuxiliaryChannel;
import com.gitee.chili.leisure.util.AuxiliaryRoom;
import com.google.protobuf.InvalidProtocolBufferException;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;

/**
 * 房间解散
 *
 * @author week solider
 * @since 2020.09.11
 */
@Slf4j
public class DissolvedRoom extends AbstractDefaultMessage {

    private Long roomNum;

    public DissolvedRoom(Packet packet, Channel channel) {
        super(packet, channel);
    }

    @Override
    protected void decoder(byte[] body) throws InvalidProtocolBufferException {
        HallModel.DissolvedRoomCmd dissolvedRoom = HallModel.DissolvedRoomCmd.parseFrom(body);

        if (Objects.isNull(dissolvedRoom)) {
            log.error("解散房间异常");
            return;
        }

        roomNum = getRoomNum();
        Long homeowner = RoomManager.obtain(roomNum).getHomeowner();

        // 只有房主才可以解散
        asserts(!getMemberId().equals(homeowner), cmd -> AuxiliaryChannel.errorMessage(getChannel(), cmd, ResponseCode.NOT_HOMEOWNER));

        SpecificTaskTransferClient transferClient = SimpleBeanFactory.getBean(SpecificTaskTransferClient.class);
        ResponseResult<Room> result = transferClient.dissolvedRoom(roomNum);
        asserts(result);
    }

    @Override
    public Packet parseBody() {
        return AuxiliaryRoom.dissolved(roomNum);
    }
}
